package dsf.eshop.commons.utils;

import java.awt.*;
import java.awt.image.BufferedImage;
import java.util.Date;
import java.util.HashMap;
import java.util.Random;

public class CaptchaUtil {

    private static final String source = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789";

    public static HashMap<String, Object> create(int width, int height, int length) {

        BufferedImage bufferedImage = new BufferedImage(width, height, BufferedImage.TYPE_INT_RGB);
        Graphics graphics = bufferedImage.getGraphics();
        graphics.fillRect(0, 0, width, height);
        graphics.setColor(Color.CYAN);
        graphics.setFont(new Font("Algerian", Font.ITALIC, 20));

        Random random = new Random(new Date().getTime());
        StringBuffer captcha = new StringBuffer(length);
        for(int i=0; i<length; i++) {

            captcha.append(source.charAt(random.nextInt(62)));
            graphics.drawString(captcha.substring(i, i+1), (i+1)*width/6, random.nextInt(height)+height/6);
        }
//        graphics.drawString(captcha.toString(), 100, 60);
        graphics.dispose();
//        bufferedImage.flush();

        HashMap<String, Object> hashMap = new HashMap<>();
        hashMap.put("captchaImage", bufferedImage);
        hashMap.put("captchaCode", String.valueOf(captcha));
        return hashMap;
    }
}
